<?php
/**
 * 通用图片类
 * Created by PhpStorm.
 * User: kb168
 * Date: 2016/11/8
 * Time: 17:11
 */
namespace soa\image;

class ImageCommon{
    
    protected $maxsize='10485760';     //文件最大上限
    protected $path='11';        //文件存储路径

    public function __construct($maxsize,$path)
    {
        $this->maxsize = $maxsize*1024*1024;
        $this->path = $path;
    }

    /**
     * 路径是否存在
     * @param $path
     * @return bool
     */
    public function isPath($path)
    {
        $allPath = array(
            'courier/realname',
            'Certificate',
            'realname/app_s',    //S端原生图片上传路径
            'order2/realname/id_card',   //实名寄递身份证照片
            'order2/realname/package',   //包裹照片
            'order2/realname/ocr',       //待识别身份证图片
        );
        if(!in_array($path,$allPath)){
            return false;
        }
        return true;
    }

    /**
     * 实名认证表单批量上传图片
     * @param $images
     * @param $courierInfo
     * @return array|bool
     */
    public function UploadFormImages($images,$courierInfo){
        $result = [];
        $uploadPath = '/upload/'.$this->path.'/';   //图片上传目录
        if(!$_FILES){
            logDebug('no files','upload_upresult','files');
        }
        if(!$this->isPath($this->path)){
            logDebug($this->path,'upload_upresult','path');
        }
        if(empty($images)){
            logDebug($images,'upload_upresult','images');
        }
        if(!$_FILES || !$this->isPath($this->path) || empty($images)){
            logDebug('disable path','upload_upresult','ispath');
            return false;
        }
        $isSuccess = 0;
        foreach ($images as $image){
            $index = $image['index']==0?'':$image['index'];
            logDebug($index,'upload_upresult','index');
            $imgStatusStr = "id_img".$index."_status";   //index 为三张图片的顺序标识
            logDebug($imgStatusStr,'upload_upresult','imgStatusStr');
            if($courierInfo[$imgStatusStr]!=1){  //存储未通过审核的图片
                    $upResult = $this->upload($_FILES[$image['title']],$uploadPath);  //上传图片  (上传file控件名,路径)
                    logDebug($upResult, 'upload_upresult','upResult');
                    $result[] = [
                        'title'  => $image['title'],
                        'index'  => $image['index'],                //图片顺序标识
                        'status' => $upResult['code'] == 0 ?1: 0,    //true：成功  false：失败
                        'path'   => $upResult['data']['path'],      //返回图片路径
                        'msg'    => $upResult['msg']
                    ];
                    if($upResult['code'] == 0){ //若图片上传成功  $imageStatus（用于是否更新数据判断）标记为1
                        $isSuccess = 1;
                    }
            }
        }
        return ['isSuccess'=>$isSuccess,'result'=>array_values($result)];
    }


    /**
     * 照片批量上传通用方法
     * @param $images
     * @return array|bool
     */
    public function UploadFormImgCom(array $images){
        $result = [];
        $uploadPath = '/upload/'.$this->path.'/';   //图片上传目录
        if(!$_FILES || !$this->isPath($this->path) || empty($images)){
            return false;
        }
        foreach ($images as $image){
            $upResult = $this->upload($_FILES[$image],$uploadPath);  //上传图片  (上传file控件名,路径)
            if($upResult['code'] == 0){ //若图片上传成功
                $result['success'][$image] = [  //上传成功图片
                    'title'  => $image,
                    'status' => 1,    //true：成功  false：失败
                    'msg'    => $upResult['msg'],
                    'path'   => $upResult['data']['path'],      //返回图片路径
                ];
            }else{
                $result['fail'][$image] = [   //上传失败图片
                    'title'  => $image,
                    'status' => 0,    //true：成功  false：失败
                    'msg'    => $upResult['msg'],
                    'path'   => $upResult['data']['path'],      //返回图片路径
                ];
            }
        }
        return $result;
    }

    /**
     * 上传图片(表单)
     * @param string $file 控件名
     * @param string $path 路径
     * @return result 文件名称
     **/
    function upload($file, $path) {
        $result = ['code'=>1,'msg'=>'上传失败','data'=>[]];
        $name = $file ["name"];
        $type = $file ["type"];
        $size = $file ["size"];
        $tmp_name =$file ["tmp_name"];
        $newname =  str_replace('.','',uniqid(TRUE,TRUE));  //生成唯一文件名
        switch ($type) {
            case 'image/pjpeg' :$extend = ".jpg";break;
            case 'image/jpeg' :$extend = ".jpg";break;
            case 'image/jpg' :$extend = ".jpg";break;
            case 'image/gif' :$extend = ".gif";break;
            case 'image/png' :$extend = ".png";break;
        }
        if (empty( $extend )) {
            $result['msg'] = '只能上传图片类型：GIF JPG PNG';
            return $result;
        }
        if ($size > $this->maxsize) {
            $result['msg'] = '上传图片大小不能超过" . $this->maxsize / 1024 . "Kb!"';
            return $result;
        }
        $savePath = $path.date('Y_m').'/'.date('d').'/';
        if(!is_dir($savePath)){ //检测目录是否存在
            if(!mkdir($savePath,0755,true)){        //尝试创建目录
                $result['msg'] = '创建目录错误';
                return $result;
            }
        }
        $imgPath = $savePath . $newname . $extend;  //图片完整路径
        if (!move_uploaded_file ( $tmp_name, $imgPath )) {
            $result['msg'] = '图片上传错误';
            return $result;
        }
        unset($newname);
        if(empty($this->getImgStream($imgPath))){     //图片内容是否为空校验
            logDebug($imgPath,'getImgStream_upload','imgPath');
            $result['msg'] = '服务器图片不能为空';
            return $result;
        }
        return ['code'=>0,'msg'=>'上传成功','data'=>['path'=>str_replace('/upload','',$imgPath)]];
    }


    /**
     * 上传图片(文件流)
     * @param $path     //图片要存储路径
     * @param $stream   //经过base64_encode编码后的图片文件流
     * @return bool|string
     */
    public function uploadStream($path,$stream)
    {
        try{
            $this->path = $path;
            $stream = str_replace(' ','+',$stream);  //图片数据流

            if($this->isPath($this->path) === false){return raise(1009,'路径有误');}
            if (empty($stream)) {return raise(1009,'缺少文件流');}

            $image = new \util\upload\UploadImage();
            $save_name = md5(mt_rand().uniqid()).'.jpg';
            $save_dir = '/upload/'.$this->path.'/';
            $result = $image->stream2Image($save_name, $save_dir, $stream, true);   //上传图片
            if(empty($result)){return raise(1010,'kb-1010-上传失败');}
            return $result;
        }catch(Exception $e){
            logError($e->getMessage(),'');
        }
    }
    
    /**
     * 判定一个图片的大小并压缩
     * $filePath 图片的路径.
     */
    public function pictureSizeGzip($sfilePath){
        $save_dir = '/upload/';
        $filePath =$save_dir.$sfilePath;
        $img_size = ceil(filesize($filePath) / 1024); //"k";
        if($img_size >= 512){ //超过512K进行压缩处理
            $temp = pathinfo($filePath);
            $image_path_new = rtrim(str_replace($temp['extension'],'', $filePath),'.').'_gz_.'.$temp['extension'];
            $this->image_png_size_add($filePath, $image_path_new);
             //当目标图片存在，且大于10K就删除原来的图片
            $this->delSrcImage($filePath, $image_path_new);
            $dfilePath = str_replace($save_dir,'',$image_path_new);           
            return $dfilePath;
        }else{
            return $sfilePath;
        }
    }
    
    //当目标图片存在，且大于10K就删除原来的图片
    private function delSrcImage($sfilePath,$dfilePath){
         $img_size = ceil(filesize($dfilePath) / 1024); //"k";
        if(file_exists($dfilePath) && $img_size>=10){
            if(!unlink($sfilePath)){
                logDebug('ImageCommon_delSrcImage:删除图片失败'.$sfilePath,'ImageCommon_delSrcImage');
            }
        }
    }
    
    /** 
    * desription 压缩图片 
    * @param sting $imgsrc 图片路径 
    * @param string $imgdst 压缩后保存路径 
    */
    private function image_png_size_add($imgsrc,$imgdst){ 
      list($width,$height,$type)=getimagesize($imgsrc); 
      $new_width = ($width>800?800:$width)*0.9; 
      $new_height =($height>600?600:$height)*0.9; 
      switch($type){ 
        case 1: 
          $giftype=$this->check_gifcartoon($imgsrc); 
          if($giftype){ 
            header('Content-Type:image/gif'); 
            $image_wp=imagecreatetruecolor($new_width, $new_height); 
            $image = imagecreatefromgif($imgsrc); 
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
            imagejpeg($image_wp, $imgdst,75); 
            imagedestroy($image_wp); 
          } 
          break; 
        case 2: 
          header('Content-Type:image/jpeg'); 
          $image_wp=imagecreatetruecolor($new_width, $new_height); 
          $image = imagecreatefromjpeg($imgsrc); 
          imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
          imagejpeg($image_wp, $imgdst,75); 
          imagedestroy($image_wp); 
          break; 
        case 3: 
          header('Content-Type:image/png'); 
          $image_wp=imagecreatetruecolor($new_width, $new_height); 
          $image = imagecreatefrompng($imgsrc); 
          imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
          imagejpeg($image_wp, $imgdst,75); 
          imagedestroy($image_wp); 
          break; 
      } 
    } 

    /** 
    * desription 判断是否gif动画 
    * @param sting $image_file图片路径 
    * @return boolean t 是 f 否 
    */
    private function check_gifcartoon($image_file){ 
      $fp = fopen($image_file,'rb'); 
      $image_head = fread($fp,1024); 
      fclose($fp); 
      return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true; 
    }

    /**
     * 获取图片(文件流)
     * @param $path     //图片完整路径
     * @return string
     */
    public function getImgStream($path)
    {
        try{
//            if(!file_exists($path)){return false;}
            $stream = file_get_contents($path);
            if(empty($stream)){return false;}
            return base64_encode($stream);
        }catch(Exception $e){
            logError($e->getMessage(),'');
        }
    }



}
